import crypto from 'crypto-js'
import store from '@/store'
import { baseUrl } from '@/utils/config'
import * as utils from '@/utils'

const VERSION_CODE = '20191028'
const APP_TYPE_QQ = 'applet-qq'

/**
 * 对请求参数签名
 * @param {Number} timestamp 时间戳
 * @param {string} appType app type
 * @param {obj} params 参数对象
 */
function signUrl(timestamp, appType = 'applet-qq', params) {
  let paramsMap = Object.assign({}, params)
  paramsMap.apptype = appType
  paramsMap.timestamp = timestamp
  paramsMap.versioncode = VERSION_CODE
  let keys = Object.keys(paramsMap)
  let content = ''

  keys.sort().filter((v) => {
    return v
  }).forEach(function (key) {
    //数组不参与签名
    let v = paramsMap[key]
    if (typeof (v) == 'undefined' || v == null) return
    if (v instanceof Array) return
    let value = '' + v
    value = value.replace(/\*/g, '')
    value = value.replace(/[ ]/g, '')
    // value = value.replace(/[\f\r\t\v]+/g, '')
    // value = value.replace(/\s\n/g, '')
    if (value) {
      value = encodeURIComponent(value)
      value = replaceEscapeChar(value)
      content += `${key}=${value}&`
    }
  })
  if (content.length > 0) {
    content = content.substring(0, content.length - 1)
  }
  // console.error('参与签名字符串:==>' + content)
  let sign = crypto.MD5(content)
  return sign.toString()
}

/**
 * 替换所有encodeURIComponent未编码的字符
 */
function replaceEscapeChar(text) {
  if (!text) {
    return text
  }
  text = text.replace(/\(/g, escape('('))
  text = text.replace(/\)/g, escape(')'))
  text = text.replace(/\~/g, escape('~'))
  text = text.replace(/\./g, escape('.'))
  text = text.replace(/\*/g, escape('*'))
  text = text.replace(/\'/g, escape('\''))
  text = text.replace(/_/g, escape('_'))
  text = text.replace(/!/g, escape('!'))
  return text
}

/**
 * 提示函数
 * 禁止点击蒙层、显示一秒后关闭
 */
const tip = msg => {
  uni.showToast({
    title: msg,
    icon: 'none',
    mask: false
  });
}

const loading = () => {
  uni.showLoading({
    title: ''
  });
}

const hide = () => {
  uni.hideLoading();
}

export const requset = (params, b = {}) => {
  if (b.load) {  //1隐藏 2显示
    loading();
  }
  let appType = APP_TYPE_QQ;
  let timestamp = +new Date();
  let sign;
  if (b.method === 'get' || b.method === 'delete') {
    //get或delete时只对url签名
    sign = crypto.MD5(encodeURIComponent(b.url)).toString()
  } else {
    sign = signUrl(timestamp, appType, params)
  }
  //需要添加头部
  let header = Object.assign({}, (params.header || {}), {
    'Content-Type': 'application/json;charset=UTF-8',
    'apptype': appType,
    'versioncode': VERSION_CODE,
    'sign': sign,
    'timestamp': timestamp,
    'token': store.state.user.token
  })
  // console.log(header)
  return new Promise((resolve, reject) => {
    let type = b.method ? b.method : 'post'
    uni.request({
      method: type,
      url: baseUrl + b.url,
      data: utils.clearAll(params),
      header: header,
      success(res) {
        if (res.data.status == 1000) {
          resolve(res.data.content)
        } else if (res.data.status == 219 || res.data.status == 218) {
          // 登陆失效
          uni.reLaunch({
            url: '/pages/authorize/index?invalid=1'
          });
        } else {
          tip(res.data.message)
		  reject(res.data.message)
        }
      },
      fail(err) {
        reject(err)
      },
      complete() {
        hide()
      }
    })
  })
}
